import {useMutation, useQuery, useQueryClient} from "@tanstack/vue-query";
import {dictApi} from "@/api/sys/dict.js";
import {computed} from "vue";


export const useDictItems = (code) => {
    return useQuery({
        queryKey: ["sysDictItems", code],
        queryFn: () => dictApi.getDictItems(code),
        // 缓存时间5分钟
        staleTime: 5 * 60 * 1000,
    })
}

// 分页查询字典类型
export const useSysDictPage = (paramsRef) => {
    return useQuery({
        queryKey: computed(() => ["sysDictPage", paramsRef.value.page, paramsRef.value.pageSize]),
        queryFn: () => dictApi.getPage({...paramsRef.value}),
        // 缓存时间5分钟
        staleTime: 5 * 60 * 1000,
    })
}

// 根据ID获取字典类型详情
export const useSysDictById = (idRef) => {
    return useQuery({
        queryKey: computed(() => ["sysDictById", idRef.value]),
        queryFn: () => dictApi.getById(idRef.value),
        // 缓存时间5分钟
        staleTime: 5 * 60 * 1000,
        enabled: computed(() => !!idRef.value)
    })
}

// 根据字典ID获取字典项列表
export const useSysDictItemsByDictId = (dictIdRef) => {
    return useQuery({
        queryKey: computed(() => ["sysDictItemsByDictId", dictIdRef.value]),
        queryFn: () => dictApi.getDictItemsByDictId(dictIdRef.value),
        // 缓存时间5分钟
        staleTime: 5 * 60 * 1000,
        enabled: computed(() => !!dictIdRef.value)
    })
}

// 字典类型增删改查
export const useSysDictMutations = () => {
    const queryClient = useQueryClient()

    // 缓存失效统一方法
    const invalidateDictCaches = async (id) => {
        // 刷新字典类型分页列表
        await queryClient.invalidateQueries({queryKey: ['sysDictPage'], exact: false});
        // 刷新字典类型详情（如果提供了 id）
        if (id) {
            await queryClient.invalidateQueries({queryKey: ['sysDictById', id]});
        }
    };

    // 删除字典类型
    const deleteById = useMutation({
        mutationFn: (id) => dictApi.delete(id),
        onSuccess: async () => {
            await invalidateDictCaches();
        }
    })

    // 批量删除字典类型
    const deleteBatch = useMutation({
        mutationFn: (ids) => dictApi.deleteBatch(ids),
        onSuccess: async () => {
            await invalidateDictCaches();
        }
    })

    // 创建字典类型
    const create = useMutation({
        mutationFn: (data) => dictApi.create(data),
        onSuccess: async () => {
            await invalidateDictCaches();
        }
    })

    // 更新字典类型
    const update = useMutation({
        mutationFn: (data) => dictApi.update(data),
        onSuccess: async (_, data) => {
            await invalidateDictCaches(data.id);
        }
    })

    return {deleteById, deleteBatch, create, update}
}
